package com.fingard.dsp.bank.directbank.wjzf02;

import com.fingard.constant.Format;
import com.fingard.crypto.SignVerifyHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.wjzf02.hessian.CCPMDownloadClient;
import com.fingard.dsp.bank.directbank.wjzf02.hessian.CCPMUploadClient;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import cacps.DownloadFileService;
import cacps.UploadFileService;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class WJZF02SinglePay extends WJZF02Base implements ISinglePay {

	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
		// 返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail tmpRetDetail;
		tmpRetDetail = d_190802(p_req1908, retAts);

		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
		}
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	private RetAtsSglDetail d_190802(ReqSingle p_req1908, RetAtsSingle retAts) throws Exception {
		RetAtsSglDetail retDetail = new RetAtsSglDetail();
		ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
		String feeNO = getBankConfig().getMapValueByKey("feeNO1908", p_req1908.singleDetail.useType);
		boolean isChecked = true;
		String chkMsg = "";
		if (actItem == null) {
			isChecked = false;
			chkMsg = "未找到账号" + p_req1908.singleDetail.payAct + "的配置";
		}
		if (StringHelper.isNullOrEmpty(feeNO)) {
			isChecked = false;
			if (chkMsg.length() > 0) {
				chkMsg = chkMsg + "；";
			}
			chkMsg = "未找到代收费项代码";
		}
		if (!isChecked) {
			RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
			tmpRetDetail.respCode = "0";
			tmpRetDetail.respInfo = chkMsg;
			tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			tmpRetDetail.transState = PaymentState.FAIL_Batch;
			tmpRetDetail.payInfoCode = "E9981";
			return tmpRetDetail;
		}
		String ownAct = p_req1908.singleDetail.payAct;
		if(StringHelper.hasAnyChar(actItem.actMapped)){
			ownAct = actItem.actMapped;
		}
		WJZF02Header header = new WJZF02Header();
		header.CorpNo = actItem.corpCode;
		header.Version = "V1.00";
		header.TranCode = "20601";
		header.FeeNo = feeNO;
		XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
		writeCommonHeader(xmlWriter, header);
		XElement tmpXElement = new XElement("In", "");
		tmpXElement.addChild(new XElement("SerialNum", p_req1908.singleDetail.askNumber));
		tmpXElement.addChild(new XElement("DbtrActName", p_req1908.singleDetail.payName));
		tmpXElement.addChild(new XElement("DbtrActId", ownAct));
		tmpXElement.addChild(new XElement("CdtrActName", p_req1908.singleDetail.recName));
		tmpXElement.addChild(new XElement("CdtrActId", p_req1908.singleDetail.recAct));
		tmpXElement.addChild(new XElement("CdtrActType", "02"));// 没有字典
		tmpXElement.addChild(new XElement("DrctCdtrBankId", ""));// 清算行行号 选填
		tmpXElement.addChild(new XElement("CdtrBankId", p_req1908.singleDetail.cnapsCode));// 收款行行号
		tmpXElement.addChild(new XElement("CdtrBankName", p_req1908.singleDetail.recBankName));// 收款行银行名字
		String bankCode = this.convertBankToBank(p_req1908.singleDetail.recBankCode);
		if(StringHelper.isNullOrEmpty(bankCode)){
			bankCode = p_req1908.singleDetail.recBankCode;
		}
		tmpXElement.addChild(new XElement("CdtrBankType", bankCode));// 收款行银行类别
		tmpXElement.addChild(new XElement("CdtrBankProvince", p_req1908.singleDetail.getOppProvinceAndCity2()[0]));// 收款省
		tmpXElement.addChild(new XElement("CdtrBankCity", p_req1908.singleDetail.getOppProvinceAndCity2()[1]));// 收款市
		tmpXElement.addChild(new XElement("PayAmt", p_req1908.singleDetail.payAmount));// 没有字典
		tmpXElement.addChild(new XElement("Remark", p_req1908.singleDetail.memo));
		tmpXElement.addChild(new XElement("Use", p_req1908.singleDetail.purpose));
		xmlWriter.writeXElement(tmpXElement);
		xmlWriter.writeEndDocument();

		// CFCA证书加密
		String cerPath = actItem.oppCertFilePath;
		String pfxPath = actItem.ownKeyStorePath;
		SignVerifyHelper signVerifyHelper = new SignVerifyHelper();
		this.WriteBankLogStep2(xmlWriter.toXmlString());
		String signbyte = signVerifyHelper.signDateByCFCA(xmlWriter.toXmlString(), cerPath);
		String signStr = new BASE64Encoder().encode(signbyte.getBytes());
		CCPMUploadClient load = new CCPMUploadClient();
		UploadFileService service = load.getUploadFileService(bankFront.serverUpload);
		String returnXml1 =null;
		returnXml1= service.asyncRealTimeSingle(actItem.userCode, actItem.corpCode, header.TranCode, signStr);
		WriteBankLogLn2("发送银行：" + "asyncRealTimeSingle 异步方法： " + "userCode :" + actItem.userCode + "  corpCode:" + actItem.corpCode
				+ " TranCode:" + header.TranCode + " signStr:" + signStr);
		
		/*if(p_req1908.reqHeader.commandCode.equals("190802A")){
			returnXml1= service.asyncRealTimeSingle(actItem.userCode, actItem.corpCode, header.TranCode, signStr);
			WriteBankLogLn2("发送银行：" + "asyncRealTimeSingle 异步方法： " + "userCode :" + actItem.userCode + "  corpCode:" + actItem.corpCode
					+ " TranCode:" + header.TranCode + " signStr:" + signStr);
		}
		else{
			returnXml1= service.realTimeSingle(actItem.userCode, actItem.corpCode, header.TranCode, signStr);
			WriteBankLogLn2("发送银行：" + "realTimeSingle 同步方法： " + "userCode :" + actItem.userCode + "  corpCode:" + actItem.corpCode
					+ " TranCode:" + header.TranCode + " signStr:" + signStr);
		}*/
		
		// 解密
		String str = new String(new BASE64Decoder().decodeBuffer(returnXml1));
		String returnXml = "";
		try {
			returnXml = signVerifyHelper.unEnvelopByCFCA(str, pfxPath, cerPath, actItem.ownKeyPassword);
		} catch (Exception e) {
			throw new Exception("验签返回报文失败");
		}
		WriteBankLogStep3(returnXml);
		retDetail = getDetailFromRetBkStr(returnXml);
		if (retDetail.respCode.equals("-1") || StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
		}
		return retDetail;
	}

	/**
	 * 单笔支付查询接口
	 * @param p_req1944
	 */
	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
		// 返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();

		ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "");
		String feeNO = getBankConfig().getMapValueByKey("feeNO1908", "");
		boolean isChecked = true;
		String chkMsg = "";
		if (actItem == null) {
			isChecked = false;
			chkMsg = "未找到账号" + p_req1944.payAct + "的配置";
		}
		if (StringHelper.isNullOrEmpty(feeNO)) {
			isChecked = false;
			if (chkMsg.length() > 0) {
				chkMsg = chkMsg + "；";
			}
			chkMsg = "未找到代收费项代码";
		}
		if (!isChecked) {
			RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
			tmpRetDetail.respCode = "0";
			tmpRetDetail.respInfo = chkMsg;
			tmpRetDetail.reqSeqID = p_req1944.askNumber;
			tmpRetDetail.transState = PaymentState.FAIL_Batch;
			tmpRetDetail.payInfoCode = "E9981";
			retAts.writeRetDetail(tmpRetDetail);
			return retAts;
		}
		String corpNo = actItem.corpCode;
		String bizDate = Format.Date8Format.format(p_req1944.getBgnDateTime());
		String tranCode = "20601";
		String serialNum = p_req1944.askNumber;
		CCPMDownloadClient cdownload = new CCPMDownloadClient();
		DownloadFileService tmpService = cdownload.getDownloadFileService(bankFront.serverDownload);
		
		String tmpBankRet = "";
		String useNewQrySglPay = getBankConfig().getValueAsString("useNewQrySglPay");
		if ("true".equals(useNewQrySglPay)) {
			tmpBankRet = tmpService.queryRealTimeSingleBySerialNum_NH(corpNo, bizDate, tranCode, feeNO, serialNum);
			WriteBankLogLn2("发送银行：" + "queryRealTimeSingleBySerialNum_NH 查询方法： " + "corpNo :" + corpNo + "  bizDate:" + bizDate
					+ " tranCode:" + tranCode + " feeNo:" + feeNO + "serialNum:" + serialNum);
		} else {
			tmpBankRet = tmpService.queryRealTimeSingleBySerialNum(corpNo, bizDate, tranCode, feeNO, serialNum);
			WriteBankLogLn2("发送银行：" + "queryRealTimeSingleBySerialNum 查询方法： " + "corpNo :" + corpNo + "  bizDate:" + bizDate
					+ " tranCode:" + tranCode + " feeNo:" + feeNO + "serialNum:" + serialNum);
		}
		
		WriteBankLogStep3(tmpBankRet);
		tmpRetAtsDetail = getDetailFromRetBkStr(tmpBankRet);
		if (tmpRetAtsDetail.respCode.equals("-1") || StringHelper.isNullOrEmpty(tmpRetAtsDetail.reqSeqID)) {
			tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
		}
		retAts.writeRetDetail(tmpRetAtsDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}

	private RetAtsSglDetail getDetailFromRetBkStr(String p_retBkStr) throws Exception {
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.respCode = "-1";
		StringBuilder tmpSbMsg = new StringBuilder();
		// 解析银行返回
		XmlTextReader tmpBkReader = loadBankRespXmlReader(p_retBkStr, tmpSbMsg);
		if (tmpBkReader != null) {
			String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/ResFlag");
			tmpRetDetail.respCode = "0";
			if (tmpRetCode.equals("0")) {
				tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Message/Head/ErrorMsg");
				tmpRetDetail.transState = tmpRetCode + "+" + tmpBkReader.getFirstText("/Message/Head/ErrorCode");
				tmpRetDetail.payInfoCode = tmpRetDetail.transState;
			} else if (tmpRetCode.equals("1")) {
				tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/Message/Out/SerialNum");
				tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Message/Out/RetMsg");
				tmpRetDetail.transState = tmpRetCode + "+" + tmpBkReader.getFirstText("/Message/Out/RetCode");
				tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/Message/Out/RetCode");
				
				if(StringHelper.hasAnyChar(tmpRetDetail.respInfo)){
					if(tmpRetDetail.respInfo.indexOf("-") > 0){
						String[] tmpPickStr = tmpRetDetail.respInfo.split("-");
						if(StringHelper.hasAnyChar(tmpPickStr[0])){
							tmpRetDetail.payInfoCode = tmpPickStr[0];
						}
						else{
							tmpRetDetail.payInfoCode = tmpRetDetail.respInfo;
						}
					}
					else{
						tmpRetDetail.payInfoCode = tmpRetDetail.respInfo;
					}
				}
			}
		} else {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = tmpSbMsg.toString();
		}
		return tmpRetDetail;
	}
}
